package dao;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import util.HibernateUtil;

public class RepositoryBase {

    public Integer salvar(Object obj) throws Exception {
        Transaction transacao = null;
        Session sessao = null;
        Integer codigo = 0;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();
            codigo = (Integer) sessao.save(obj);
            transacao.commit();
        } catch (HibernateException ex) {
            transacao.rollback();
            Logger.getLogger(RepositoryBase.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            sessao.close();
        }
        return codigo;
    }

    public void salvarAlterar(Object obj) throws Exception {
        Session sessao = HibernateUtil.getSessionFactory().openSession();
        Transaction transacao = sessao.beginTransaction();
        sessao.saveOrUpdate(obj);
        transacao.commit();
        sessao.close();
    }

    public void alterar(Object obj) throws Exception {
        Transaction transacao = null;
        Session sessao = null;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();
            sessao.update(obj);
            transacao.commit();
        } catch (HibernateException ex) {
            transacao.rollback();
            Logger.getLogger(RepositoryBase.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            sessao.close();
        }
    }

    public void excluir(Object obj) throws Exception {
        Transaction transacao = null;
        Session sessao = null;
        try {
            sessao = HibernateUtil.getSessionFactory().openSession();
            transacao = sessao.beginTransaction();
            sessao.delete(obj);
            transacao.commit();
        } catch (HibernateException ex) {
            transacao.rollback();
            Logger.getLogger(RepositoryBase.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            sessao.close();
        }
    }
}
